public class L110 {
    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(3);
        TreeNode treeNode9 = new TreeNode(9);
        TreeNode treeNode20 = new TreeNode(20);
        treeNode.left = treeNode9;
        treeNode.right = treeNode20;
        TreeNode treeNode15 = new TreeNode(15);
        TreeNode treeNode7 = new TreeNode(7);
        treeNode20.left = treeNode15;
        treeNode20.right = treeNode7;

        boolean balanced = new Solution().isBalanced(treeNode);
        System.out.println(balanced);

    }

    static class Solution {
        public boolean isBalanced(TreeNode root) {
            int depth = getDepth(root);
            return depth != -1;

        }

        private int getDepth(TreeNode root) {
            if (root == null) return 0;
            int depth = getDepth(root.left);
            if (depth == -1) {
                return -1;
            }
            int depth1 = getDepth(root.right);
            if (depth1 == -1) {
                return -1;
            }
            if (Math.abs(depth - depth1) > 1) {
                return -1;
            }
            return Math.max(depth, depth1) + 1;
        }
    }
}
